<template>
  <div class="page-all-content-pr">
    <div class="left-panel-container">
      <div class="img_left_title">
        <img src="../assets/img/module2/content.png" style="width: 100%" />
        <img src="../assets/img/module2/snailtitleicon.png" style="position: absolute; top: -10%; left: 6%" />
        <span class="text_left_title">空域使用说明文件</span>
      </div>

      <button v-if="!tableVisible" class="table-button-display" @click="tableVisible = true"></button>
      <button v-if="tableVisible" class="table-button-hidden" @click="tableVisible = false"></button>

      <!-- 功能输入按钮部分 -->
      <div v-if="tableVisible" class="table-actions">
        <!-- 搜索框 -->
        <input type="text" v-model="searchQuery" placeholder="请输入关键字" class="search-input" />
        <!-- 查询按钮 -->
        <button @click="filterTable" class="filter-button"></button>
        <!-- 排序选择 -->
        <select v-model="selectedSort" class="sort-select" @change="sortTable">
          <option value="application_acceptance_time" class="sort-select-item">按时间最新</option>
          <option value="id" class="sort-select-item">按序号排序</option>
        </select>
        <button @click="sortInverse" class="sort-button"></button>
        <!-- <el-switch
          v-model="switchValue"
          active-color="#13ce66"
          inactive-color="#3f93ff"
          @change="handleSwitchChange"
        >
        </el-switch> -->
      </div>

      <!-- 表格内容 -->
      <div v-if="tableVisible" class="table-context">
        <CustomTable :data="tableData" :columns="columns" @viewDetails="handleViewDetails" @hoverLeave="hoverLeave"
          @viewDetailsHover="handleViewDetailsHover" height="100%" ref="customTable" />
      </div>
    </div>

    <!-- 弹窗内容 -->
    <div class="right-panel-container">
      <CustomDialog :visible.sync="statusDialogVisible" :selectedDetails="selectedDetails"
        @submitClickTransfer="submitVisibleChange" @userClickTransfer='userVisibleChange' ref="statusDialog"
        @entity-change="entityViewChange">
      </CustomDialog>
    </div>

    <!-- 用户选择 -->
    <CustomDialogUserChoose :visible.sync="userChooseDialogVisible" width="1200px" height="600px">
    </CustomDialogUserChoose>
    <!-- 发布确认 -->
    <!-- <CustomDialogReleaseConfirm :visible.sync="cofirmReleaseDialogVisible" width="600px" height="300px">
    </CustomDialogReleaseConfirm> -->
    <CustomDialogReleaseUser :visible.sync="cofirmReleaseDialogVisible" :title="selectedDetails.programName"
      :users="userList" :proid="selectedDetails.id" @refreshHistory="refreshHistory"> </CustomDialogReleaseUser>
  </div>
</template>

<script>
import ListTitle from "@/components/ListTitle";
import CustomTable from '@/components/CustomTableModule2PlanningRelease.vue';
// import CustomTable from '@/components/CustomTableModule2PlanningScheme.vue';
import CustomDialogReleaseConfirm from '@/components/CustomDialogModule2ReleaseConfirm.vue';
import CustomDialogReleaseUser from '@/components/CustomDialogModule2ReleaseUser.vue';
import CustomDialogUserChoose from '@/components/CustomDialogModule2UserChoose.vue';
import CustomDialog from '@/components/CustomDialogModule2PRInformation.vue';
import { drawCylinderAreaM1, draw3DRectangularPipelineTrackM1_2, draw3DPolygonalPrismM1 } from '@/utils/draw3D-module2.js';
import axios from 'axios';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE2;

export default {
  name: "Module2PlanningRelease",
  props: {
    cesiumViewer: {
      type: Object,
      required: true
    }
  },
  components: {
    CustomTable,
    CustomDialogReleaseConfirm,
    CustomDialogReleaseUser,
    CustomDialog,
    CustomDialogUserChoose,
    ListTitle
  },
  data() {
    return {
      tableVisible: true, // 表格显示
      statusDialogVisible: false,  // 状态弹窗显示
      cofirmReleaseDialogVisible: false,
      userChooseDialogVisible: false,
      selectedDetails: {}, // 存储选中的行数据
      selectedSort: 'id', // 默认按序号排序
      searchQuery: '',  // 搜索关键字
      inverseSort: true, // 排序顺序，默认升序
      fileList: [], // 上传文件列表
      tableData: [], // 表格数据从服务器获取
      userList: [], // 用户列表
      gisdata: [],
      entityMap: {},
      viewer: null,
      currentLabelEntity: null,
      currentColor: null,
      currentEntityType: null,
      columns: [
        { prop: 'id', label: '#', width: '8%' },
        { prop: 'fileName', label: '空域使用说明', width: '45%' },
        { prop: 'publishingTime', label: '发布时间', width: '47%' },
      ],
      switchValue: false, // switch 开关的状态
      currentDrawEntities: [], // 用于存储当前函数绘制的实体
    }
  }, 
  created() {
    // 页面加载时获取数据
    this.fetchTableData();
    this.fetchUserData();
    // 将传入的 viewer 实例赋值给组件的 data
    this.viewer = this.cesiumViewer
    console.log("Module6子组件获得的this.viewer", this.viewer)
  },
  mounted() {
  },
  beforeDestroy() {
    console.log("module2组件销毁，开始清除GIS实体");
    this.clearCurrentDrawEntities();
  },
  methods: {
    handleSwitchChange(val) {
      console.log('开关状态改变:', val)
    },
    // 绘制gis数据
    async drawgis(row) {
      try {
        console.log("此时的entities", this.viewer.entities)
        // 清除上一次绘制的实体
        this.clearCurrentDrawEntities();
        // this.viewer.entities.removeAll();
        this.refreshGISdata(); // 刷新gis数据
        this.fetchGISData(row); // 获取gis数据

        const { circular, polygonal, straight } = this.gisdata;
        const entitiesToFlyTo = [];
        console.log("规划方案页面绘制GIS的数据", this.gisdata)

        // 绘制圆柱体
        if (circular.length > 0) {
          circular.forEach((coord, index) => {
            const entity = drawCylinderAreaM1(
              this.viewer,
              coord.longitude,
              coord.latitude,
              coord.minAltitude,
              coord.maxAltitude,
              coord.radius,
              coord.color,
              0.2,
              coord.text,
            );
            if (entity) {
              entity.properties = new Cesium.PropertyBag({
                index: coord.index,  // 自定义index字段
                activeIndex: coord.activeidentityid,  // 自定义activeIndex字段
                type: 'circular',
                fromCurrentDrawPR: true, // 添加标识
              });

              //暂时去掉
              // this.gisdata.circular[index].entity = entity; 
              this.addEntity(coord.activeidentityid, coord.index, entity);
              this.currentDrawEntities.push(entity); // 记录当前绘制的实体
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制多边形柱体
        if (polygonal.length > 0) {
          polygonal.forEach((track, index) => {
            // 检查 coordinates 是否存在且长度大于0
            if (track.coordinates && Array.isArray(track.coordinates) && track.coordinates.length > 0) {
              // console.log("绘制多边形柱状体传入的数据", track)
              // console.log("经纬度坐标信息", track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat())
              // console.log("最小高度", track.minAltitude)

              const entity = draw3DPolygonalPrismM1(
                this.viewer,
                track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat(),
                track.minAltitude,
                track.maxAltitude,
                track.color,
                0.2,
                track.text
              );
              // console.log("entity", entity)
              // console.log("index", index)
              if (entity) {
                entity.properties = new Cesium.PropertyBag({
                  index: track.index,  // 自定义index字段
                  activeIndex: track.activeidentityid,  // 自定义activeIndex字段
                  type: 'polygonal', //多变形体设置为1，为了后续改颜色获取实体本体
                  fromCurrentDrawPR: true, // 添加标识
                });
                entitiesToFlyTo.push(entity);
                this.addEntity(track.activeidentityid, track.index, entity);
                this.currentDrawEntities.push(entity); // 记录当前绘制的实体
              }
            } else {
              console.log(`Track ${index} 的 coordinates 数据为空或未定义`);
            }
          });
        }


        // 绘制长方体管道轨迹
        if (straight.length > 0) {
          console.log("绘制长方体管道传入的数据", straight);
          straight.forEach((track, index) => {
            // const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
            const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, track.maxAltitude]).flat();
            const pointNames = track.activeidentityid; // 获取每个轨迹点的名字

            // Ensure sizes array has the correct length
            // const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]); // 对应生成每段长宽
            const sizes = new Array(coordinates.length / 3 - 1).fill([100, track.maxAltitude - track.minAltitude]);

            // Check if sizes length matches coordinates length - 1
            if (sizes.length !== coordinates.length / 3 - 1) {
              console.error('Sizes array length does not match coordinates array length minus one');
            } else {
              const entities = draw3DRectangularPipelineTrackM1_2(
                this.viewer,
                coordinates,
                sizes,
                0.2,
                track.color,
                track.text,
                // pointNames // 传递轨迹点名字数组
              );
              if (entities) {
                // console.log("typeof entities",entities);
                entities.forEach((entity, num) => {
                  entity.properties = new Cesium.PropertyBag({
                    index: track.index,  // 自定义index字段
                    activeIndex: track.activeidentityid,  // 自定义activeIndex字段,
                    type: 'straight',
                    fromCurrentDrawPR: true, // 添加标识
                  });
                  this.currentDrawEntities.push(entity); // 记录当前绘制的实体
                  entitiesToFlyTo.push(entity);
                  console.log('添加实体', num)
                })
                //暂时去掉
                this.addEntity(track.activeidentityid, track.index, entities);
              }
            }
          });
        }

        // 调整实体视角
        if (entitiesToFlyTo.length > 0) {
          this.viewer.flyTo(entitiesToFlyTo, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些

            }
          });
        }

        console.log("entityMap", this.entityMap)

        // 鼠标左键点击事件
        this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
          // 清除之前的标签实体
          // if (currentLabelEntity) {
          //   this.viewer.entities.remove(currentLabelEntity);
          //   currentLabelEntity = null;
          // }
          const pickedObject = this.viewer.scene.pick(movement.position, 5);

          if (pickedObject && pickedObject.id && pickedObject.id.properties && pickedObject.id.properties.activeIndex) { // console.log("pickedObject", pickedObject)
            // console.log("pickedObject.id", pickedObject.id)
            // console.log("pickedObject.id.properties", pickedObject.id.properties)
            // console.log("pickedObject.id.properties.index", pickedObject.id.properties.index.getValue())
            // console.log("pickedObject.id.properties.activeIndex", pickedObject.id.properties.activeIndex.getValue())
            // console.log(this.$refs.statusDialog)
            // this.$refs.statusDialog.testClick()
            const id1 = pickedObject.id.properties.activeIndex.getValue()
            const id2 = pickedObject.id.properties.index.getValue()
            const type = pickedObject.id.properties.type.getValue()
            this.$refs.statusDialog.clickGis(id1, id2)
            this.viewer.flyTo(this.getEntity(id1, id2), {
              duration: 2,
              offset: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
                range: 16000
              }
            })

            this.entityChangeColor(this.getEntity(id1, id2), type)
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        console.log('方案地图组件渲染成功');
      } catch (error) {
        console.error('方案地图组件渲染失败', error);
      }
    },
    // 清除当前组件绘制函数创建的实体
    clearCurrentDrawEntities() {
      if (this.currentDrawEntities.length > 0) {
        this.currentDrawEntities.forEach(entity => {
          if (this.viewer.entities.contains(entity)) {
            this.viewer.entities.remove(entity);
          }
        });
        this.currentDrawEntities = []; // 清空数组
      }
    },
    entityChangeColor(entityAgent, type) {
      // 上一个点击的实体恢复颜色
      if (this.currentLabelEntity) {
        this.currentColor.alpha = 0.2;
        if (this.currentEntityType == 'straight') {
          this.currentLabelEntity.forEach(entity => {
            if (entity.material && entity.material.color) {
              entity.material.color = this.currentColor;
            }
          });
        } else {
          if (this.currentLabelEntity.material && this.currentLabelEntity.material.color) {
            this.currentLabelEntity.material.color = this.currentColor;
          }
        }
      }

      // 更新当前实体的种类
      this.currentEntityType = type;

      // 对当前点击的实体进行颜色变化
      if (type === 'circular') {
        this.currentLabelEntity = entityAgent.cylinder;
      } else if (type === 'polygonal') {
        this.currentLabelEntity = entityAgent.polygon;
      } else if (type === 'straight') {
        this.currentLabelEntity = entityAgent.map(entity => entity.corridor);
      }

      if (this.currentEntityType == 'straight') {
        if (this.currentLabelEntity && this.currentLabelEntity[0] && this.currentLabelEntity[0].material && this.currentLabelEntity[0].material.color) {
          this.currentColor = this.currentLabelEntity[0].material.color.getValue(Cesium.JulianDate.now()).clone();
          this.currentColor.alpha = 1;
          this.currentLabelEntity.forEach(entity => {
            if (entity.material && entity.material.color) {
              entity.material.color = this.currentColor;
            }
          });
        } else {
          console.error('Error: No valid material found for straight entities');
        }
      } else {
        if (this.currentLabelEntity && this.currentLabelEntity.material && this.currentLabelEntity.material.color) {
          this.currentColor = this.currentLabelEntity.material.color.getValue(Cesium.JulianDate.now()).clone();
          this.currentColor.alpha = 1;
          this.currentLabelEntity.material.color = this.currentColor;
        } else {
          console.error('Error: No valid material found for the entity');
        }
      }
      console.log('完成实体的变色');
    },
    // 销毁Cesium实例
    cesiumDestroy() {
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      console.log(this.viewer);
    },
    async fetchGISData(row) {
      console.log('row.takeoffLandInfo', row.takeoffLandInfo)
      console.log('row.airlineInfo', row.airlineInfo)
      console.log('row.workInfo', row.workInfo)
      console.log('row.specialInfo', row.specialInfo)
      // 更新GIS数据，使gisdata的值符合作图的形式
      row.takeoffLandInfo && row.takeoffLandInfo.forEach((detail, index) => {
        console.log('正在处理起降机场数据:', detail)
        this.takeofflandpush(detail, index, 'main1')
      });


      // 遍历航路信息并根据 type 使用不同的颜色绘制
      row.airlineInfo && row.airlineInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          let color = 'RED'; // 默认颜色为红色
          switch (detail.type) {
            case 0:
              color = 'CHOCOLATE';  // 低速航路
              break;
            case 1:
              color = 'ORANGE';  // 中速航路
              break;
            case 2:
              color = 'CORNFLOWERBLUE';  // 高速航路
              break;
            case 3:
              color = "DARKCYAN";  // 匝道
              break;
          }

          this.straightpush(
            shape.points,              // 点数据
            shape.minAltitude,         // 底部高度
            shape.maxAltitude,         // 顶部高度
            index,                     // 索引
            'main2',                   // 信息 ID
            detail.name,               // 航路名称
            color                   // 颜色（示例）
          );
          console.log(`多边形柱体航路（类型 ${detail.type}）更新`);
        });
      });

      // 遍历作业区信息并根据 shapeType 调用相应的绘制方法
      row.workInfo && row.workInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          if (shape.shapeType === 1) { // 圆柱体类型 1
            this.cirularpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('圆柱体更新');
          } else if (shape.shapeType === 2) { // 另一种圆柱体类型 2（目前使用相同绘制方法）
            this.cirularpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('圆柱体（类型 2）更新');
          } else if (shape.shapeType === 3) { // 多边形柱体
            this.polygonalpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('多边形柱体更新');
          }
        });
      });

      // 遍历特殊区域信息并根据 shapeType 调用相应的绘制方法
      row.specialInfo && row.specialInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          if (shape.shapeType === 1) { // 圆形柱体
            this.cirularpush(shape, index, 'main4', detail.name, 'RED');
            console.log('圆形柱体更新');
          } else if (shape.shapeType === 2) { // 另一种圆形柱体类型
            this.cirularpush(shape, index, 'main4', detail.name, 'RED');
            console.log('圆形柱体（类型 2）更新');
          } else if (shape.shapeType === 3) { // 多边形柱体类型
            // 创建一个新的多边形数据对象
            const polygonalData = {
              points: [],  // 存放每个点的数据
              coordinates: [],  // 存放多边形顶点的经纬度
              minAltitude: shape.minAltitude,  // 从 shape 获取最小高度
              maxAltitude: shape.maxAltitude,  // 从 shape 获取最大高度
              index: index,
              activeidentityid: 'main4',
              text: detail.name,
              color: 'RED'
            };

            // 如果存在 points 数组，遍历并提取经纬度信息
            if (shape.points && Array.isArray(shape.points) && shape.points.length > 0) {
              shape.points.forEach(point => {
                // 确保每个点都包含有效的经纬度信息
                if (point.latitude && point.longitude) {
                  // 添加点到 points 数组
                  polygonalData.points.push({
                    altitude: point.altitude,  // 如果有高度信息，存储
                    latitude: point.latitude,
                    longitude: point.longitude,
                    sequence: point.sequence,  // 如果有顺序信息，存储
                    shapeId: point.shapeId  // 如果有形状 ID，存储
                  });
                } else {
                  console.log("发现无效的点数据:", point);
                }
              });
            } else {
              console.log("没有可用的点数据 (shape.points 为空或未定义)");
            }

            // 检查是否有有效的坐标
            if (polygonalData.points.length > 0) {
              // 调用 polygonalpush 函数来绘制多边形柱体
              this.polygonalpush(polygonalData, index, 'main4', detail.name, 'RED');
              console.log('多边形柱体更新:', polygonalData);
            } else {
              console.log("没有有效的坐标数据，跳过该多边形柱体");
            }
          }
        });
      });
    },
    async fetchTableData() {
      try {
        // const response = await axios.post('http://47.99.75.194:8082/module2/search', null,
        //   {
        //     params:
        //     {
        //       sort: this.selectedSort,
        //       keyword: this.searchQuery,
        //       order: this.inverseSort,
        //     },
        //   }
        // );
        const response = await axios.post(`${baseApi}/airspaceUtilization/utisearch`, null, {
          params: {
            sort: this.selectedSort,
            keyword: this.searchQuery,
            order: this.inverseSort,
          },
        });

        if (response.data.code === 0) {
          console.log("使用说明发布页面从后端获取的所有数据:tableData", response.data.data)
          this.tableData = response.data.data;
        }
      } catch (error) {
        console.error('获取表格数据失败', error);
      }
    },
    //获取用户信息
    async fetchUserData() {
      try {
        // const response = await axios.get('http://47.99.75.194:8082/module2/GetPubUser', null, null);
        const response = await axios.get(`${baseApi}/airspaceUtilization/GetPubUser`, null, null);

        if (response.data.code === 0) {
          this.userList = response.data.data;
          console.log('获取用户信息');
          console.log(this.userList);
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },
    sortTable() {
      // 重新获取排序后的数据
      this.fetchTableData();
    },
    sortInverse() {
      this.inverseSort = !this.inverseSort;
      // console.log(this.inverseSort);
      this.fetchTableData();
    },
    filterTable() {
      // 触发搜索过滤，重新获取数据
      this.fetchTableData();
    },
    refreshTable() {
      // 刷新表格数据，重置搜索和排序
      this.selectedSort = 'id';
      this.searchQuery = '';
      this.fetchTableData();
    },
    refreshHistory() {
      // 刷新历史数据，通知子组件完成
      setTimeout(() => { this.$refs.statusDialog.fetchHistoryData(this.selectedDetails.id); }, 100);
    },
    handleViewDetails(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
      this.cofirmReleaseDialogVisible = false; // 关闭确认弹窗 后续优化的话可以在弹窗时直接设置无法点击别处
      this.$refs.statusDialog.refreshChange();
      this.drawgis(row);
      this.$refs.statusDialog.fetchHistoryData(row.id);

    },
    handleViewDetailsHover(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
    },
    hoverLeave() {
      this.statusDialogVisible = false;
    },
    submitVisibleChange() {
      this.cofirmReleaseDialogVisible = true;
    },
    userVisibleChange() {
      this.userChooseDialogVisible = true;
    },
    // 添加实体函数
    addEntity(id1, id2, entity) {
      const key = `${id1}-${id2}`;  // 组合 id1 和 id2 作为唯一键
      this.entityMap[key] = entity;  // 存储实体
    },
    // 获取实体函数
    getEntity(id1, id2) {
      const key = `${id1}-${id2}`;  // 组合 id1 和 id2 生成键
      return this.entityMap[key];  // 获取对应实体
    },
    entityViewChange(id1, id2, type) {
      // console.log(id1,id2);
      console.log(id1, id2);
      if (Cesium.defined(this.getEntity(id1, id2))) {
        this.viewer.flyTo(this.getEntity(id1, id2), {
          duration: 2,
          offset: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
            range: 16000
          }
        })
        this.entityChangeColor(this.getEntity(id1, id2), type)
      }

    },
    refreshGISdata() {
      this.gisdata = {
        circular: [],
        polygonal: [],
        straight: []
      };
    },
    takeofflandpush(detail, index, infoid) {
      // 第一句话后续可以去掉 注意数据类型
      // console.log("typeof detail",typeof detail);
      // console.log("降落机场detail",detail);
      // detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      // this.gisdata.circular.push(
      //   {
      //     longitude: detail.longitude,
      //     latitude: detail.latitude,
      //     minAltitude: 100,
      //     maxAltitude: 800,
      //     radius: 1200,
      //     activeidentityid: infoid,
      //     index: index,
      //     color: 'YELLOW',
      //     text: detail.airportType + '区',
      //   })
      const shape = detail.shapes[0].shapes[0]; // 获取 shapes 中的第一个 shape 对象
      const centerPoint = shape.points[0]; // 圆心点坐标信息

      // 构建圆柱体的 GIS 数据
      this.gisdata.circular.push({
        longitude: centerPoint.longitude,
        latitude: centerPoint.latitude,
        minAltitude: shape.minAltitude,
        maxAltitude: shape.maxAltitude,
        radius: shape.rout, // 使用 rout 作为半径
        activeidentityid: infoid,
        index: index,
        color: 'YELLOW',
        text: detail.name + '区',
      });

      console.log("起降机场数据已添加至 GIS 数据:", this.gisdata.circular);
    },
    cirularpush(shape, index, infoid, text, color) {
      // console.log("圆形detail", detail);
      // // detail=JSON.parse(detail.replace(/([{,])\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":'));
      // this.gisdata.circular.push(
      //   ...detail.map(coord => ({
      //     longitude: coord.longitude,
      //     latitude: coord.latitude,
      //     minAltitude: coord.minAltitude,
      //     maxAltitude: coord.maxAltitude,
      //     radius: coord.radius,
      //     activeidentityid: infoid,
      //     index: index,
      //     text: text,
      //     color: color

      //   })))
      console.log("圆柱体 shape detail:", shape);

      // 圆柱体的中心点信息从 shape.points[0] 获取
      const centerPoint = shape.points[0];

      this.gisdata.circular.push({
        longitude: centerPoint.longitude,
        latitude: centerPoint.latitude,
        minAltitude: shape.minAltitude,
        maxAltitude: shape.maxAltitude,
        radius: shape.rout, // 使用 rout 作为半径
        activeidentityid: infoid,
        index: index,
        color: color,
        text: text,
      });

      console.log("圆柱体已添加至 GIS 数据:", this.gisdata.circular);
    },
    polygonalpush(shape, index, infoid, text, color) {

      // console.log("多边形detail", detail);
      // const polygonalData = {
      //   coordinates: [],  // 存放经纬度数组
      //   minAltitude: null,  // 存放最小高度数组
      //   maxAltitude: null, // 存放最大高度数组
      //   index: index,
      //   activeidentityid: infoid,
      //   text: text,
      //   color: color

      // };
      // const firstPoint = detail[0];
      // polygonalData.minAltitude = firstPoint.minAltitude;
      // polygonalData.maxAltitude = firstPoint.maxAltitude;

      // detail.forEach(point => {
      //   // 将经纬度信息推入 coordinates 数组
      //   polygonalData.coordinates.push({
      //     longitude: point.longitude,
      //     latitude: point.latitude
      //   });
      // });
      // console.log(polygonalData);
      // this.gisdata.polygonal.push(polygonalData);
      console.log("多边形 detail:", shape);

      // 构建多边形数据
      const polygonalData = {
        coordinates: [],  // 存放多边形顶点的经纬度
        minAltitude: shape.minAltitude,  // 从 shape 获取最小高度
        maxAltitude: shape.maxAltitude,  // 从 shape 获取最大高度
        index: index,
        activeidentityid: infoid,
        text: text,
        color: color
      };

      // // 遍历 points 中的每个顶点并提取经纬度
      // shape.points.forEach(point => {
      //   polygonalData.coordinates.push({
      //     longitude: point.longitude,
      //     latitude: point.latitude
      //   });
      // });
      // 检查 shape.points 是否存在且是一个数组
      if (shape.points && Array.isArray(shape.points) && shape.points.length > 0) {
        // 遍历 points 中的每个顶点并提取经纬度
        shape.points.forEach(point => {
          polygonalData.coordinates.push({
            longitude: point.longitude,
            latitude: point.latitude
          });
        });
      } else {
        console.log("没有可用的顶点数据 (shape.points 为空或未定义)");
      }


      // 添加到 GIS 数据结构的多边形列表中
      this.gisdata.polygonal.push(polygonalData);
      console.log("多边形柱体已添加至 GIS 数据:", this.gisdata.polygonal);
    },
    // straightpush(detail, index, infoid, text, color) {
    //   console.log('点线形航路数据', detail);

    //   // 构建 straight 数据结构
    //   const straightData = {
    //     coordinates: [],  // 包含经纬度和高度的数组
    //     index: index,
    //     activeidentityid: infoid,
    //     color: color,
    //     text: text,
    //   };

    //   detail.forEach(point => {
    //     // 推入每个点的坐标信息
    //     straightData.coordinates.push({
    //       longitude: point.longitude,
    //       latitude: point.latitude,
    //       altitude: point.altitude
    //     });
    //   });

    //   // 添加到 GIS 数据的 straight 部分
    //   this.gisdata.straight.push(straightData);
    //   console.log('straightData 已添加至 GIS 数据:', straightData);
    // },
    straightpush(points, minAltitude, maxAltitude, index, infoid, text, color) {
      console.log('点线形航路数据:', points);

      // 构建 straight 数据结构
      const straightData = {
        coordinates: [],           // 包含经纬度和高度的数组
        minAltitude: minAltitude,  // 底部高度
        maxAltitude: maxAltitude,  // 顶部高度
        index: index,
        activeidentityid: infoid,
        color: color,
        text: text
      };

      // 遍历 points，提取经纬度和高度信息
      points.forEach(point => {
        straightData.coordinates.push({
          longitude: point.longitude,
          latitude: point.latitude,
          altitude: point.altitude
        });
      });

      // 添加到 GIS 数据的 straight 部分
      this.gisdata.straight.push(straightData);
      console.log('straightData 已添加至 GIS 数据:', straightData);
    },
  },
  watch: {
    // 监听 statusDialogVisible 的变化
    statusDialogVisible(newValue, oldValue) {
      if (newValue === false && oldValue === true) {
        // 当 statusDialogVisible 从 1 变为 0 时，调用子组件的 resetSelection 方法
        this.$refs.customTable.resetSelection();
        // console.log('resetSelection called');
      }
    }
  }

}
</script>

<style scoped lang="css">
.cesiumContainerBox {
  width: 100%;
  position: relative;
  height: 80vh;
  margin: 0;
  padding: 0;

  .mapBg {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    pointer-events: none;
  }

  .layer {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 2;
    pointer-events: none;
    box-shadow: inset -200px 0px 60px -20px rgb(6 7 29 / 35%), inset 200px 0px 60px -20px rgb(6 7 29 / 35%);
  }
}

/* 调整 switch 的位置 */
.el-switch {
  position: absolute;
    background-size: contain; /* 背景图片覆盖按钮大小 */
    background-repeat: no-repeat;
    background-color: transparent;
    color:transparent;
    left: 41%;
    top: 11%;
    height: 60%;
    z-index: 3;
    border: none;
    cursor: pointer;
}

</style>
<style scoped lang="css" src="../assets/indexModule2PR.css" />